package web.commons;

import domain.ImageEntry;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.ImageService;


public class ImagePanel extends Panel {
    @SpringBean
    private ImageService imageService;

    public ImagePanel(String id, IModel<ImageEntry> model) {
        super(id, model);

        ResourceReference ref = new ResourceReference("imageResource");

        boolean available = false;
        Long imageId = null;
        if (model.getObject() != null) {
            imageId = model.getObject().getId();
            try {
                available = imageService.isImageAvailable(model.getObject());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String url = getRequestCycle().urlFor(ref) + "/imageEntryId/" + imageId;
        ExternalLink eLink = new ExternalLink("imageLink", url);
        add(eLink);
        eLink.setVisible(available);

        url = url + "/thumbnail/true";
        AttributeModifier modifier = new AttributeModifier(
                "src",
                new Model(url));
        Label label = new Label("thumbnailImage", "");
        eLink.add(label);
        label.add(modifier);
        label.setVisible(available);

        label = new Label("thumbnailImageNA", "");
        add(label);
        label.add(modifier);
        label.setVisible(!available);
    }
}
